package com.lhd.controller;
import com.lhd.component.RedisComponent;
import com.lhd.entity.constants.Constants;
import com.lhd.entity.dto.UserDto;
import com.lhd.entity.enums.ResponseCodeEnum;
import com.lhd.entity.vo.ResponseVO;
import com.lhd.exception.BusinessException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ABaseController {
    @Resource
    private RedisComponent redisComponent;
    protected static final String STATUS_SUCCESS = "success";

    protected static final String STATUS_ERROR = "error";
    // 常用
    protected <T> ResponseVO getSuccessResponseVO(T t) {
        ResponseVO<T> responseVO = new ResponseVO<>();
        responseVO.setStatus(STATUS_SUCCESS);
        responseVO.setCode(ResponseCodeEnum.CODE_200.getCode());
        responseVO.setInfo(ResponseCodeEnum.CODE_200.getMsg());
        responseVO.setData(t);
        return responseVO;
    }

    // 获取UserInfoToken
    protected UserDto getUserInfoToken(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String token = request.getHeader(Constants.AUTHORIZATION);
            String uuid = token;
            if (token.contains("Bearer")){
                uuid = token.substring(7);
            }
            String key = Constants.REDIS_KEY + Constants.TOKEN + uuid;
            return redisComponent.getUserInfoDto(key);
        }
        return new UserDto();
    }


    /**
     * @description: 将token存入cookie 因为有些请求没法向请求头中加token
     * @param response
     * @param token
     * @return
     * @author liuhd
     * 2025/3/18 21:24
     */

    protected void saveTokenToCookie(HttpServletResponse response, String token) {
        // cookie是键值对
        Cookie cookie = new Cookie("token", token);
        // 过期时间
        cookie.setMaxAge(Constants.ONE_DAY_H * 7);
        cookie.setPath("/");
        // 放入response中
        response.addCookie(cookie);
    }
}
